# -*-  conding: utf-8 -*-
# Author: czh
# Datetime : 2022/5/9 13:12
import time

import numpy as np
import tushare as ts
from pprint import pprint
import pandas as pd
from datetime import date, timedelta, datetime
from jiucai import isopenday

# # 获取今天的日期，并转化成相应格式
import xlwt as xlwt

day = date.today()
today = format(day.strftime('%Y%m%d'))
# 初始化pro接口  陈
# pro = ts.pro_api('cf37ab059637ac7f5d628bdd046a9bcb2c1e34c2fa7546e6b8659225')

# 初始化pro接口  康
pro = ts.pro_api('3b52e2e8f4f8de54e3d662f06b62ef3373da8593d8428776cb2af432')


#
# def get_next_date(ts_code, start_date, name):
#     """ 根据日期获取未来五个交易日的增幅 ts_code:股票代码600313.SH ； start_date：开始时间"""
#     try:
#         open_day_list = isopenday.open_day_list
#         index = open_day_list.index(start_date)
#         # 下一个交易日
#         next_day = open_day_list[index + 6]
#         # 拉取数据
#         time.sleep(0.1)
#         # 拉取数据
#         pct_chg = pro.daily(
#             **{"ts_code": ts_code, "trade_date": "", "start_date": start_date, "end_date": next_day,
#                "offset": "",
#                "limit": ""
#                },
#             fields=["ts_code", "trade_date", "open", "high", "low", "close", "pre_close", "change", "pct_chg", "vol",
#                     "amount"
#                     ])
#
#         next_pic = pct_chg.iloc[5, 8]
#         next_one_pct = pct_chg.iloc[4, 8]
#         next_two_pct = pct_chg.iloc[3, 8]
#         next_three_pct = pct_chg.iloc[2, 8]
#         next_four_pct = pct_chg.iloc[1, 8]
#         next_five_pct = pct_chg.iloc[0, 8]
#
#         # print("下一个不知道符不符合：", next_pic)
#         if 6 <= next_pic <= 11:
#             print("下一个符合符合符合符合符合符合：", next_pic)
#             return name, next_day, next_pic, next_one_pct, next_two_pct, next_three_pct, next_four_pct, next_five_pct
#     except:
#         print("遇到一个错误：", name)
#
#
# if __name__ == '__main__':
#
#     """ 获取每只股票的当天数据 """
#     # 拉取数据:
#     """
#     01ts_code股票代码 02trade_date交易日期 03open开盘价 04high最高价 05low最低价 06close收盘价 07pre_close昨收价 08change涨跌额 09pct_chg涨跌幅 10vol成交量 11amount成交额"""
#     print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
#     name_list = []
#     next_day_list = []
#     next_pic_list = []
#     next_one_pct_list = []
#     next_two_pct_list = []
#     next_three_pct_list = []
#     next_four_pct_list = []
#     next_five_pct_list = []
#
#     fuhe_list = []
#     # f_csv = pd.read_csv("shishi.csv", skiprows=1, nrows=700)
#     f_csv = pd.read_csv("shishi.csv")
#     for index, data1 in f_csv.iterrows():
#         #  获取股票代码，名称
#         name = data1[2]
#         symbol = data1[1][2:] + "." + data1[1][:2].upper()
#         print("开始执行第{0}支股票:{1}".format(index, name))
#
#         df = pro.daily(**{
#             "ts_code": symbol, "trade_date": "", "start_date": 20210509, "end_date": 20220511, "offset": "",
#             "limit": ""
#         }, fields=["ts_code", "trade_date", "open", "high", "low", "close", "pre_close", "change", "pct_chg", "vol",
#                    "amount"
#                    ])
#
#         for idx, data in df.iterrows():
#             # 提取数据
#             trade_date = data[1]
#             today_pct = float(data[8])
#             if -11 <= today_pct <= -6:
#                 next_pct = get_next_date(symbol, trade_date, name)
#                 if next_pct is not None:
#                     fuhe_list.append(next_pct)
#                     name_list.append(next_pct[0])
#                     next_day_list.append(next_pct[1])
#                     next_pic_list.append(next_pct[2])
#                     next_one_pct_list.append(next_pct[3])
#                     next_two_pct_list.append(next_pct[3])
#                     next_three_pct_list.append(next_pct[3])
#                     next_four_pct_list.append(next_pct[3])
#                     next_five_pct_list.append(next_pct[3])
#     #   保存至Excel
#     pd.DataFrame({"股票名称": name_list, "先跌再涨的涨幅": next_pic_list, "下一日交易日期": next_day_list,
#                   "第一日的涨幅": next_one_pct_list, "第二日的涨幅": next_two_pct_list, "第三日的涨幅": next_three_pct_list,
#                   "第四日的涨幅": next_four_pct_list, "第五日的涨幅": next_five_pct_list}).to_excel(
#         "下跌和上涨2.xlsx")
#     print(fuhe_list)
#     print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))


class Vxian:
    def get_date(self):
        """获取最近的四个交易日"""
        today_date = time.strftime('%Y%m%d', time.localtime())
        # 拉取数据
        df = pro.trade_cal(**{
            "start_date": today_date,
            "limit": 1,
        }, fields=["exchange", "cal_date", "is_open", "pretrade_date"
                   ])
        # 判断是否是交易日
        pretrade_date = df.iloc[0, 3]
        is_open = df.iloc[0, 2]
        if is_open == 1:
            # 如果是交易日，返回下标，获取最近三天的交易日
            today_date_index = isopenday.open_day_list.index(today_date)
            three_date_list = isopenday.open_day_list[today_date_index - 4:today_date_index]
            print(three_date_list)
            return three_date_list, today_date
        # 如果不是交易日，找最近三天的交易日
        else:
            today_date_index = isopenday.open_day_list.index(pretrade_date)
            three_date_list = isopenday.open_day_list[today_date_index - 3: today_date_index + 1]
            print(three_date_list)
            return three_date_list

    def get_Xdie_symbol(self):
        """ 获取下跌前4个交易日涨跌幅超过6且后面几日超过6的股票 """
        symbol_list = []
        trade_date_list = []
        three_date_list = self.get_date()

        for trade_date in three_date_list:
            # 循环判断最近几天是否有涨跌幅低于6的股票
            print(trade_date)
            trade_date_index = three_date_list.index(trade_date)
            df = pro.daily(trade_date=trade_date)
            df = df[df["pct_chg"] <= -6]
            # 根据筛选出来的股票和交易日，算出到最近一个交易日的涨跌幅大于6的数据
            for index, data in df.iterrows():
                try:
                    new_df = pro.daily(ts_code=data[0], start_date=three_date_list[trade_date_index], end_date=three_date_list[-1])
                    new_df = new_df[new_df["pct_chg"] >= 6]
                    if not new_df.empty:
                        print(data[0], new_df.iloc[0, 8])
                        symbol_list.append(data[0])
                        # trade_date_list.append(data[1])
                except:
                    print("出错一个")
        pd.DataFrame({"股票代码": symbol_list}).to_excel(
            "下跌和上涨4.xlsx")
        print(len(symbol_list))
        return symbol_list
        # 转换成列表,并合并
        #     df_list = np.array(df["ts_code"]).tolist()
        #     symbol_list.extend(df_list)
        # symbol_list = list(set(symbol_list))
        # return symbol_list

    # def get_Szhang_symbol(self):
    #     """根据下跌股票到最近一个交易日的数据，如果涨跌幅大于6的股票筛选出来，"""
    #     three_date_list = self.get_date()
    #     symbol_list = self.get_Xdie_symbol(three_date_list)
    #     for symbol_tuple in symbol_list:
    #         symbol = symbol_tuple[0]
    #         trade_date = symbol_tuple[1]


if __name__ == '__main__':
    print(Vxian().get_Xdie_symbol())
